<template>
    <div class="gesture-picker">
      <el-form-item  prop="gesture">
        <div class="nine-grid-container">
          <!-- 九宫格布局 -->
          <div 
            class="grid-wrapper"
            @mousedown="handleStart"
            @mousemove="handleMove"
            @mouseup="handleEnd"
            @touchstart.prevent="handleStart"
            @touchmove.prevent="handleMove"
            @touchend.prevent="handleEnd"
          >
            <div 
              v-for="point in points" 
              :key="point.id"
              class="grid-point"
              :class="{ active: selectedPoints.includes(point.id) }"
              :style="{
                left: `${point.x}%`,
                top: `${point.y}%`
              }"
            ></div>
            <canvas ref="canvasRef" class="draw-canvas"></canvas>
          </div>
          
          <div class="gesture-controls">
            <el-button @click="clearCanvas">清除</el-button>
            <el-button type="primary" @click="confirmGesture">确认</el-button>
          </div>
        </div>
      </el-form-item>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, defineEmits, defineExpose } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  
  const API_BASE = 'http://localhost:8080/session'
  const api = {
    create: `${API_BASE}/addGesture`,
  }

  // 九宫格点配置
  const points = reactive([
    { id: 1, x: 10, y: 10 },  // 左上
    { id: 2, x: 50, y: 10 },  // 中上
    { id: 3, x: 90, y: 10 },  // 右上
    { id: 4, x: 10, y: 50 },  // 左中
    { id: 5, x: 50, y: 50 },  // 中心
    { id: 6, x: 90, y: 50 },  // 右中
    { id: 7, x: 10, y: 90 },  // 左下
    { id: 8, x: 50, y: 90 },  // 中下
    { id: 9, x: 90, y: 90 }   // 右下
  ])
  
  // 状态管理
  const canvasRef = ref(null)
  const selectedPoints = ref([])
  const isDrawing = ref(false)
  const gestureData = reactive({
    sessionType: '手势',
    patternCode: ''
  })
  let ctx = null
  const emit = defineEmits(['update:modelValue'])
  
  // 初始化画布
  onMounted(() => {
    ctx = canvasRef.value.getContext('2d')
    const { width, height } = canvasRef.value.getBoundingClientRect()
    canvasRef.value.width = width
    canvasRef.value.height = height
    ctx.strokeStyle = '#409eff'
    ctx.lineWidth = 4
    ctx.lineCap = 'round'
  })
  
  // 事件处理
  const handleStart = (e) => {
    isDrawing.value = true
    clearCanvas()
    checkPoint(e)
  }
  
  const handleMove = (e) => {
    if (!isDrawing.value) return
    checkPoint(e)
    drawLine()
  }
  
  const handleEnd = () => {
    isDrawing.value = false
    ctx.closePath()
  }
  
  // 检查触摸点
  const checkPoint = (e) => {
    const rect = canvasRef.value.getBoundingClientRect()
    const x = (e.touches ? e.touches[0].clientX : e.clientX) - rect.left
    const y = (e.touches ? e.touches[0].clientY : e.clientY) - rect.top
  
    points.forEach(point => {
      const pointX = (point.x / 100) * rect.width
      const pointY = (point.y / 100) * rect.height
      const distance = Math.sqrt((x - pointX) ** 2 + (y - pointY) ** 2)
      
      if (distance < 20 && !selectedPoints.value.includes(point.id)) {
        selectedPoints.value.push(point.id)
        drawCircle(pointX, pointY)
      }
    })
  }
  
  // 绘制辅助方法
  const drawCircle = (x, y) => {
    ctx.beginPath()
    ctx.arc(x, y, 15, 0, Math.PI * 2)
    ctx.fillStyle = '#409eff'
    ctx.fill()
  }
  
  const drawLine = () => {
    if (selectedPoints.value.length < 2) return
    
    ctx.beginPath()
    const rect = canvasRef.value.getBoundingClientRect()
    const pointsToDraw = selectedPoints.value.map(id => 
      points.find(p => p.id === id)
    )
    
    pointsToDraw.forEach((point, index) => {
      const x = (point.x / 100) * rect.width
      const y = (point.y / 100) * rect.height
      if (index === 0) {
        ctx.moveTo(x, y)
      } else {
        ctx.lineTo(x, y)
      }
    })
    
    ctx.stroke()
  }
  
  // 清除画布
  const clearCanvas = () => {
    ctx.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height)
    selectedPoints.value = []
    gestureData.patternCode = ''
    emit('update:modelValue', '')
  }
  
  // 确认手势
  const confirmGesture = () => {
    if (selectedPoints.value.length < 4) {
      ElMessage.warning('至少需要连接4个点')
      return
    }
    
    if (new Set(selectedPoints.value).size !== selectedPoints.value.length) {
      ElMessage.warning('不能重复连接相同点')
      return
    }
    
    gestureData.patternCode = selectedPoints.value.join('-')
    emit('update:modelValue', gestureData.patternCode)
    ElMessage.success('手势已保存')
  }
  
  // 验证方法
  const validate = () => {
    if (!gestureData.patternCode) {
      ElMessage.warning('请绘制并确认手势')
      return false
    }
    const points = gestureData.patternCode.split('-')
    if (points.length < 4) {
      ElMessage.error('至少需要连接4个点')
      return false
    }
    return true
  }
  
  // 提交处理（保持不变）
  const handleCreate = async () => {
    const payload = {
      sessionType: '手势签到',
      patternCode: gestureData.patternCode
    };
  
    try {
      const response = await axios.post(api.create, payload)
      emit('update:modelValue', response.data.patternCode)
      return response.data
    } catch (error) {
      throw new Error('手势提交失败')
    }
  };
  
  defineExpose({
    validate,
    handleCreate,
    clearCanvas
  })
  </script>
  
  <style scoped>
  .nine-grid-container {
    position: relative;
    width: 350px;
    height: 350px;
    margin: 20px auto;
  }
  
  .grid-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .draw-canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    touch-action: none;
  }
  
  .grid-point {
    position: absolute;
    width: 20px;
    height: 20px;
    background: #eee;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    transition: background 0.3s;
  }
  
  .grid-point.active {
    background: #409eff;
    box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
  }
  
  .gesture-controls {
    margin-top: 15px;
    display: flex;
    gap: 10px;
    justify-content: center;
  }
  </style>